<template>
  <view class="container">
    <map 
      :latitude="latitude" 
      :longitude="longitude" 
      :markers="markers"
      scale="15"
      style="width: 100%; height: 80vh;"
    />
	
	<view class="contBig">
		<view class="iconBox">
			<image src="/static/home/mywz.png" mode=""></image>
		</view>
		<view class="contBox">
		<!-- 	<view class="contMyAddress">
				<view class="contMyAddressTop">
					<view class="contMyAddressTit">
						门店地址
					</view>
					<view class="contMyAddressBtn" @click="reLocation">
						重新定位
					</view>
				</view>
				<view class="contMyAddressText">
					{{ storeAddress.address || '获取门店信息中...' }}
				</view>
			</view> -->
			<view class="contLi">
				<view class="contName">
					拍照（必填）
				</view>
				<view class="contImg" @click="takePhoto">
					<image v-if="photoPath" :src="photoPath" mode="aspectFill" style="width: 100%; height: 100%; border-radius: 19.23rpx;"></image>
					<u-icon v-else name="camera-fill" color="#000000" size="28"></u-icon>
				</view>
			</view>
			<view class="contLi" style="display: block;">
				<view class="contName">
					备注（必填）
				</view>
				<view class="contTextarea">
					<textarea 
						placeholder="请填写备注" 
						placeholder-style="color: #B8B8B8;"
						v-model="remark"
						maxlength="100"
						@input="handleRemarkInput"
					></textarea>
					<view class="contTextareaNum" :class="{ 'warning': remark.length > 90 }">
						{{ remark.length }}/100
					</view>
				</view>
			</view>
			<view class="footerBtn" @click="submitCheckIn" :class="{ 'disabled': !canSubmit }">
                {{ currentTime }} {{ checkLabel }}
      </view>
			
			<!-- 调试信息区域：打卡失败时展示接口返回 -->
			<view v-if="showDebug" class="debugBox">
				<view class="debugTitle">调试信息（打卡返回）</view>
				<scroll-view scroll-y style="max-height: 200rpx;">
					<text class="debugContent">{{ debugText }}</text>
				</scroll-view>
				<view class="debugActions">
					<view class="closeBtn" @click="showDebug = false">关闭</view>
				</view>
			</view>
		</view>
	</view>
  </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed, watch } from 'vue'
import { createShopCheck, uploadImage } from '@/api/interface.js'

// 响应式数据
const latitude = ref(0)
const longitude = ref(0)
const currentAddress = ref('')
const storeAddress = ref('')
const photoPath = ref('')
const remark = ref('')
const currentTime = ref('')
const markers = ref([])
const shopInfo = ref(null)
let locationUpdateStarted = false
let timer = null

// 新增：调试区域状态
const showDebug = ref(false)
const debugResult = ref(null)
const debugText = computed(() => {
  try {
    return JSON.stringify(debugResult.value, null, 2)
  } catch (e) {
    return String(debugResult.value)
  }
})
// 动态文案：根据后端状态显示“进店/离店打卡”
const checkLabel = computed(() => {
  if (!shopInfo.value) return '到店打卡'
  return shopInfo.value.clockInAfterWork ? '离店打卡' : '到店打卡'
})
// 计算属性：是否可以提交打卡
const canSubmit = computed(() => {
  return photoPath.value && remark.value.trim().length > 0 && shopInfo.value && latitude.value > 0 && longitude.value > 0
})

// 更新当前时间
const updateTime = () => {
  const now = new Date()
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  const seconds = String(now.getSeconds()).padStart(2, '0')
  currentTime.value = `${hours}:${minutes}:${seconds}`
}

// 处理备注输入
const handleRemarkInput = () => {
  // 自动处理输入逻辑已通过v-model绑定
}

// 拍照功能
const takePhoto = () => {
  uni.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    sourceType: ['camera'],
    success: (res) => {
      photoPath.value = res.tempFilePaths[0]
    },
    fail: (err) => {
      console.error('拍照失败', err)
      if (err.errMsg !== 'chooseImage:fail cancel') {
        uni.showToast({ title: '拍照失败', icon: 'none' })
      }
    }
  })
}

// 重新定位
const reLocation = () => {
  uni.showLoading({ title: '定位中...' })
  startLocationUpdate()
}

// 地址解析（根据经纬度获取地址）
const getAddressByLocation = (lat, lng) => {
  return new Promise((resolve, reject) => {
    uni.request({
      url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${lat},${lng}&key=IQJBZ-2TTKZ-PC3XJ-TGMT3-6IYP2-VWB7K`, // 请替换为实际的地图服务KEY
      success: (res) => {
        if (res.data && res.data.status === 0) {
          resolve(res.data.result.address)
        } else {
          reject(new Error('地址解析失败'))
        }
      },
      fail: (err) => {
        reject(err)
      }
    })
  })
}

// 启动定位
const startLocationUpdate = () => {
  // 先请求权限
  uni.authorize({
    scope: 'scope.userLocation',
    success: () => {
      uni.startLocationUpdate({
        success: () => {
          console.log('✅ 开始后台位置更新')
          locationUpdateStarted = true

          // 监听位置变化
          uni.onLocationChange((res) => {
            console.log('📍 位置更新:', res)
            latitude.value = res.latitude
            longitude.value = res.longitude
            
            // 更新地图标记（用户位置）
            updateMarkers(res.latitude, res.longitude)
          })
        },
        fail: (err) => {
          console.error('❌ 启动定位失败', err)
          uni.hideLoading()
          uni.showToast({ title: '定位启动失败', icon: 'none' })
        }
      })
    },
    fail: () => {
      uni.hideLoading()
      uni.showToast({ title: '需要定位权限', icon: 'none' })
      setTimeout(() => {
        uni.openSetting() // 引导用户去设置页开启
      }, 1000)
    }
  })
}

// 更新地图标记
const updateMarkers = (userLat, userLng) => {
  const newMarkers = []
  
  // 用户位置标记
  newMarkers.push({
    id: 1,
    latitude: userLat,
    longitude: userLng,
    title: '您的位置',
    iconPath: '/static/home/didian.png', // 使用系统中的位置图标
    width: 50,
    height: 50
  })
  
  // 店铺位置标记
  if (shopInfo.value && shopInfo.value.latitude && shopInfo.value.longitude) {
    newMarkers.push({
      id: 2,
      latitude: shopInfo.value.latitude,
      longitude: shopInfo.value.longitude,
      title: shopInfo.value.name || shopInfo.value.shopName || '打卡门店',
      iconPath: '/static/home/shopIcon.png', // 使用系统中的店铺图标
      width: 50,
      height: 50
    })
  }
  
  markers.value = newMarkers
}

// 提交打卡
const submitCheckIn = async () => {
  if (!canSubmit.value) {
    uni.showToast({ title: '请完成所有必填项', icon: 'none' })
    return
  }
  
  uni.showLoading({ title: '打卡中...' })
  
  try {
    // 使用新的上传图片接口
    console.log('开始上传图片...')
    const uploadResult = await uploadImage(photoPath.value, 'checkin')
    let imgUrl = photoPath.value // 如果上传失败，暂时使用本地路径
    
    if (uploadResult && uploadResult.url) {
      imgUrl = uploadResult.url
      console.log('图片上传成功:', imgUrl)
    }
    
    // 调用打卡接口
    const params = {
      shopId: shopInfo.value.id.toString(),
      type:  shopInfo.value.clockInAfterWork ? '0': '1', // 1到店
      longitude: longitude.value.toString(),
      latitude: latitude.value.toString(),
      address: storeAddress.value.address,
      imgUrl: imgUrl,
      remark: remark.value.trim()
    }
    
    console.log('打卡参数:', params)
    const result = await createShopCheck(params)
    
    if (result && result.code === 0) {
      // 成功后跳转到成功页面，并传递打卡类型
      uni.hideLoading()
      uni.navigateTo({
        url: `/pages/index/checkInSuccess?type=${params.type}`
      })
    } else {
      // 不抛错，展示调试信息
      uni.hideLoading()
      uni.showToast({ title: result?.msg || '打卡失败', icon: 'none' })
      showDebug.value = true
      debugResult.value = result
    }
  } catch (error) {
    console.error('打卡失败', error)
    uni.hideLoading()
    // 发生异常也展示调试信息
    showDebug.value = true
    debugResult.value =debugResult.value + error
    uni.showToast({ 
      title: error.message || '打卡失败，请重试', 
      icon: 'none'
    })
  } finally {
    uni.hideLoading()
  }
}

// 页面加载
onMounted(async () => {
  // 初始化时间
  updateTime()
  timer = setInterval(updateTime, 1000)
  
  // 从本地存储获取店铺信息
  try {
    const storeInfo = uni.getStorageSync('currentShop')
    if (storeInfo) {
      shopInfo.value = storeInfo
      // 设置门店地址
      storeAddress.value = shopInfo.value.address || 
                          shopInfo.value.location || 
                          `${shopInfo.value.latitude || ''}, ${shopInfo.value.longitude || ''}`.trim() || 
                          '未知地址'
      console.log('获取店铺信息:', shopInfo.value)
    }
  } catch (e) {
    console.error('获取店铺信息失败', e)
  }
  
  // 设置导航标题为“进店/离店打卡”
  uni.setNavigationBarTitle({ title: checkLabel.value })
  watch(checkLabel, (t) => uni.setNavigationBarTitle({ title: t }))
  
  // 启动定位
  await startLocationUpdate()
})

// 页面卸载时清理
onUnmounted(() => {
  // 清除定时器
  if (timer) {
    clearInterval(timer)
  }
  
  // 停止定位
  if (locationUpdateStarted) {
    uni.stopLocationUpdate()
    uni.offLocationChange()
    console.log('⏹️ 停止位置更新与监听')
  }
})
</script>

<style scoped lang="scss">
.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #F2F3F5;
}

.info-box {
  padding: 15px;
  background-color: #f8f8f8;
  text-align: center;
}

.info-box text {
  display: block;
  margin-bottom: 10px;
}

.contBig{
	position: fixed;
	bottom: env(safe-area-inset-bottom);
	left: 25rpx;
}

.iconBox{
	width: 70.51rpx;
	height: 70.51rpx;
	margin-bottom: 10rpx;
	image{
		width: 100%;
		height: 100%;
	}
}
.contBox{
	width: 700rpx;
	border-radius: 19.23rpx 19.23rpx 19.23rpx 19.23rpx;
	background: #ffffff;
	padding: 40rpx;
	box-sizing: border-box;
	
	.contMyAddress{
		margin-bottom: 20rpx;
		.contMyAddressTop{
			display: flex;
			align-items: center;
			justify-content: space-between;
			.contMyAddressTit{
				font-weight: 500;
				font-size: 33.33rpx;
				color: #1C2027;
			}
			.contMyAddressBtn{
				font-size: 28.21rpx;
				font-weight: 400;
				color: #3776F5;
			}
		}
		.contMyAddressText{
			font-size: 25.64rpx;
			font-weight: 400;
			color: #7C8288;
			margin-top: 20rpx;
		}
	}
	.contLi{
		border-top: 1rpx solid #F2F3F5;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 25rpx 0;
		.contName{
			font-weight: 500;
			font-size: 33.33rpx;
			color: #1C2027;
		}
		.contImg{
			width: 94.23rpx;
			height: 94.23rpx;
			border-radius: 19.23rpx 19.23rpx 19.23rpx 19.23rpx;
			background: #ffffff;
			display: flex;
			align-items: center;
			justify-content: center;
			border: 1rpx solid #E5E5E5;
		}
		.contTextarea{
			margin-top: 20rpx;
			width: 100%;
			height: 60rpx;
			textarea{
				flex: 1;
				font-size: 29.49rpx;
				height: 100%;
			}
			.contTextareaNum{
				display: flex;
				align-items: center;
				justify-content: flex-end;
				font-size: 25.64rpx;
				font-weight: 400;
				color: #B8B8B8;
			}
			.contTextareaNum.warning{
				color: #FF3939;
			}
		}
	}
	.footerBtn{
		width: 100%;
		height: 87.18rpx;
		border-radius: 19.23rpx 19.23rpx 19.23rpx 19.23rpx;
		background: #00bd86;
		color: #ffffff;
		 font-weight: 400;
		 font-size: 35.9rpx;
		 line-height: 51.19rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-top: 30rpx;
	}
	.footerBtn.disabled{
		background: #CCCCCC;
		color: #FFFFFF;
	}
	.footerBtn.out-btn{
		background: #3776F5;
	}
	.footerBtn.out-btn.disabled{
		background: #CCCCCC;
	}
	.debugBox{
		margin-top: 20rpx;
		padding: 20rpx;
		background: #f9fafb;
		border: 1rpx solid #e5e7eb;
		border-radius: 12rpx;
	}
	.debugTitle{
		font-size: 28rpx;
		color: #1C2027;
		margin-bottom: 10rpx;
	}
	.debugContent{
		font-family: monospace;
		font-size: 24rpx;
		color: #4b5563;
	}
	.debugActions{
		display: flex;
		justify-content: flex-end;
		margin-top: 10rpx;
	}
	.closeBtn{
		padding: 10rpx 20rpx;
		border-radius: 10rpx;
		background: #e5e7eb;
		color: #374151;
	}
}
</style>